/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React from "react";
import { connect } from "dva";
import { Form, Select, Button, Popconfirm, Row, Col, Spin, message } from "antd";
import PageHeaderLayout from "@/layouts/PageHeaderLayout";
import StandardTable from "@/components/StandardTable";
import { debounce } from "lodash";
import styles from "./style.less";

const FormItem = Form.Item;
const { Option } = Select;

@connect(({ allocation, loading }) => ({
  authManagementList: allocation.authManagementList,
  provinceList: allocation.provinceList,
  cityList: allocation.cityList,
  loading: loading.effects["allocation/getAuthManagementList"],
  provinceListLoading: loading.effects["allocation/getProvinceList"],
}))
@Form.create()
class AuthorityManagement extends React.PureComponent {
  handleTableChange = debounce(
    pagination => {
      this.getList(pagination.current);
      this.setState({
        page: pagination.current,
        selectedRows: [],
      });
    },
    500,
    {
      leading: true,
      trailing: false,
    }
  );

  constructor(props) {
    super(props);
    this.state = {
      page: 1,
      selectedRows: [],
    };
    this.columns = [
      {
        title: "省级",
        dataIndex: "province",
        align: "center",
      },
      {
        title: "市级",
        dataIndex: "city",
        align: "center",
      },
      {
        title: "县级",
        dataIndex: "county",
        align: "center",
      },
      {
        title: "共配权限",
        dataIndex: "is_gp",
        align: "center",
        render: text => (text == 0 ? "已关闭" : "已开启"),
      },
      {
        title: "操作",
        align: "center",
        render: (_, record) => {
          const { is_gp, id } = record;
          const open = is_gp == 0;
          const text = open ? "开启" : "关闭";
          return open ? (
            <a onClick={() => this.changeAuth([id], open)}>{text}</a>
          ) : (
            <Popconfirm
              key={id}
              title={`确认${text}共配权限？`}
              onConfirm={() => this.changeAuth([id], open)}
            >
              <a>{text}</a>
            </Popconfirm>
          );
        },
      },
    ];
  }

  componentDidMount() {
    this.getList();
  }

  componentWillUnmount(){
    const { dispatch } = this.props
    dispatch({
      type: "allocation/save",
      payload: {
        provinceList: [],
        cityList: [],
        addressList: [],
      },
    });
  }

  changeAuth = (id = [], open) => {
    const { page } = this.state;
    const { dispatch } = this.props;

    dispatch({
      type: "allocation/changeAuth",
      payload: {
        id: id.join(","),
        is_gp: Number(open),
      },
    }).then(res => {
      const { code } = res;
      if (code == 0) {
        this.getList(page);
        this.setState({ selectedRows: [] });
      }
    });
  };

  getList = (page = 1) => {
    const { dispatch, form } = this.props;
    const { validateFields } = form;
    this.setState({
      selectedRows: [],
    })
    validateFields((err, fieldsValue) => {
      if (err) return;
      dispatch({
        type: "allocation/getAuthManagementList",
        payload: {
          page,
          pageSize: 20,
          ...fieldsValue,
        },
      });
    });
  };

  handleProvinceChange = value => {
    const { dispatch, form } = this.props;
    const { setFieldsValue } = form;
    setFieldsValue({
      city: "",
    });
    dispatch({
      type: "allocation/save",
      payload: {
        cityList: [],
      },
    });
    if (value === "") {
      return;
    }
    dispatch({
      type: "allocation/getCityList",
      payload: {
        id: value,
      },
    });
  };

  onRowSelect = (selectedRows = []) => {
    this.setState({ selectedRows });
  };

  onProvinceDropdownVisibleChange = visibale => {
    const { dispatch } = this.props;
    visibale &&
      dispatch({
        type: "allocation/getProvinceList",
        payload: {
          branch_id: 0,
        },
      });
  };

  onSubmit = () => {
    this.getList();
  };

  onBatchClick = () => {
    const { selectedRows = [] } = this.state;
    if(selectedRows.length == 0){
      message.warning("请先选择需要批量开通或关闭的地区")
    }
  }

  render() {
    const {
      form,
      authManagementList,
      loading,
      provinceList,
      cityList,
      provinceListLoading,
    } = this.props;
    const { getFieldDecorator } = form;
    const { selectedRows = [] } = this.state;
    const ids = selectedRows.map(i => i.id);
    const hasSelect = selectedRows.length > 0;
    return (
      <PageHeaderLayout title="共配权限管理">
        <div className={styles.main} style={{ position: "relative" }}>
          <Form layout="inline" className={styles.form}>
            <FormItem label="省">
              {getFieldDecorator("province", {
                initialValue: "",
              })(
                <Select
                  style={{ width: 200 }}
                  onDropdownVisibleChange={this.onProvinceDropdownVisibleChange}
                  onChange={this.handleProvinceChange}
                >
                  <Option key="" value="">
                    全部
                  </Option>
                  {provinceListLoading ? (
                    <Option disabled value="loadig">
                      <Spin />
                    </Option>
                  ) : (
                    provinceList.map(val => (
                      <Option key={val.id} value={val.id}>
                        {val.name}
                      </Option>
                    ))
                  )}
                </Select>
              )}
            </FormItem>
            <FormItem label="市">
              {getFieldDecorator("city", {
                initialValue: "",
              })(
                <Select style={{ width: 200 }}>
                  <Option key="" value="">
                    全部
                  </Option>
                  {cityList.map(val => (
                    <Option key={val.id} value={val.id}>
                      {val.name}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
            <FormItem label="状态">
              {getFieldDecorator("is_gp", {
                initialValue: "",
              })(
                <Select placeholder="请选择状态" style={{ width: 200 }}>
                  <Option key="" value="">
                    全部
                  </Option>
                  <Option key="1">已开通</Option>
                  <Option key="0">已关闭</Option>
                </Select>
              )}
            </FormItem>
            <FormItem>
              <Button type="primary" onClick={this.onSubmit}>
                查询
              </Button>
            </FormItem>
          </Form>
          <StandardTable
            rowKey="id"
            columns={this.columns}
            data={authManagementList}
            loading={loading}
            onChange={this.handleTableChange}
            selectedRows={selectedRows}
            onSelectRow={this.onRowSelect}
          />
          <Row type="flex" gutter={[10, 0]} style={{ position: "absolute", bottom: 60, left: 40 }}>
            <Col>
              <Popconfirm
                disabled={!hasSelect}
                title="确认批量开通共配权限？" 
                onConfirm={() => this.changeAuth(ids, true)}
              >
                <a onClick={this.onBatchClick} className={!hasSelect ? styles.disabled : ''}>批量开通</a>
              </Popconfirm>
            </Col>
            <Col>
              <Popconfirm
                disabled={!hasSelect}
                title="确认批量关闭共配权限？"
                onConfirm={() => this.changeAuth(ids, false)}
              >
                <a onClick={this.onBatchClick} className={!hasSelect ? styles.disabled : ''}>批量关闭</a>
              </Popconfirm>
            </Col>
          </Row>
        </div>
      </PageHeaderLayout>
    );
  }
}

export default AuthorityManagement;
